import {defineStore} from 'pinia';
import {reqCode, reqUSerLogin} from "@/api/user/index.js";
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
export const useUserStore = defineStore('User', {
    state: () => {
        return {
            dialogFormVisible: false,
            code: '',
            userInfo: JSON.parse(GET_TOKEN()) || {},
        }
    },
    actions: {
        //  获取验证码
        async getCode(phone) {
            const res = await reqCode(phone);
            if (res.code === 200) {
                this.code = res.data;
                return 'ok';
            } else {
                return Promise.reject(new Error(res.message, '验证码获取失败'));
            }
        },
        // 登录
        async getLogin(data) {
            const res = await reqUSerLogin(data);
            if (res.code === 200) {
                this.userInfo = res.data;
                localStorage.setItem('USERINFO', JSON.stringify(res.data));
                return 'ok';
            } else {
                return Promise.reject(new Error(res.message, '登录失败'));
            }
        },
        // 设置用户信息
        setUserInfo(userInfo) {
            this.userInfo = userInfo;
            localStorage.setItem('USERINFO', JSON.stringify(userInfo));
        },
        // 获取用户信息
        getUserInfo() {
            return JSON.parse(localStorage.getItem('USERINFO')) || {};
        },
        // 退出登录
        logout() {
            //清空仓库的数据
            this.userInfo = {name: '', token: ''};
            //清空本地存储的数据
            // localStorage.removeItem('USERINFO');
            //移除token
            REMOVE_TOKEN();
        },
    },

    getters: {},
})